﻿using NModBusDrive;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using TestModBus.Model;
using WinformControls.Forms;

namespace TestModBus
{
    public partial class Form4 : FrmWithTitle, ILog, IDisposable
    {
        Random rd = new Random();
        PerformanceTestModel performanceTest = new PerformanceTestModel();
        public System.Timers.Timer tmerCh = null;
        public bool IsStop { get; set; }
        public Form4()
        {
            InitializeComponent();
            Console.SetOut(new TextBoxWriter(tboxConsole));
            tmerCh = new System.Timers.Timer(800);
            tmerCh.Elapsed += new System.Timers.ElapsedEventHandler(TimerChCallBack);
            tmerCh.AutoReset = false;
            tmerCh.Enabled = false;
          
            performanceTest.bussiness.Logger = this;
            performanceTest.bussiness.serialPortUtil.CallDataReceived += SerialPortUtil_CallDataReceived;
            this.FormClosing += PerformanceTest_FormClosing;
        }
        private void PerformanceTest_FormClosing(object sender, FormClosingEventArgs e)
        {
            performanceTest.bussiness.serialPortUtil.ClosePort();
        }

        int count1 = 0;
        Thread thread;
        private void SerialPortUtil_CallDataReceived(byte[] bits)
        {
            if (IsStop)
                return;
            string str = PublicMethod.ByteToHexStr(bits);
            Console.WriteLine("返回数据-->{0}",str);
            if (str.IndexOf("FFFF") == 0) // 机械矩阵
            {
                if (bits[3] == 1)    // 动作完成
                {
                    if (count1 == 0 && thread==null)
                    {
                        thread = new Thread(() => {
                            SetSingleSingeColor(performanceTest.Ch, ColorType.Success);
                            Thread.Sleep(2000);
                            tmerCh.Enabled = true;
                        });
                        thread.Start();
                        count1++;
                    }
                }
                else if (bits[3] == 2) // X轴故障报警
                {
                    Console.WriteLine("X轴故障报警");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 3) // Y轴故障报警
                {
                    Console.WriteLine("Y轴故障报警");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 4) // Z轴故障报警
                {
                    Console.WriteLine("Z轴故障报警");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 5) // 设备处于手动状态
                {
                    Console.WriteLine("设备处于手动状态");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 6) // 设备处于急停状态
                {
                    Console.WriteLine("设备处于急停状态");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 7) // 指令冲突
                {
                    Console.WriteLine("指令冲突");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
                else if (bits[3] == 8) // 运行中切换
                {
                    Console.WriteLine("运行中切换");
                    SetSingleSingeColor(performanceTest.Ch, ColorType.Error);
                }
            }
        }

        private void TimerChCallBack(object sender, ElapsedEventArgs e)
        {
            thread = null;
            count1 = 0;
            SetCHDefaultState();
            int _i = rd.Next(1, 13);
            performanceTest.Ch = _i;
            // 切换通道矩阵
            performanceTest.ChangeCh(_i);
        }


        #region 日志
        public void Debug(string content)
        {
            Console.WriteLine(content);
        }

        public void Error(string content)
        {
            Console.WriteLine(content);
        }

        public void Error(Exception ex)
        {
            Console.WriteLine(string.Format("{0}\r\n{1}", ex.Message, ex.StackTrace));
        }

        public void Info(string content)
        {
            Console.WriteLine(content);
        }

        public void Write(string log)
        {
            Console.WriteLine(log);
        }

        #endregion

        private void BtClear_Click(object sender, EventArgs e)
        {
            this.tboxConsole.Clear();
        }

        private void BtTest_Click(object sender, EventArgs e)
        {
            SetCHDefaultState();
            IsStop = false;
            tmerCh.Enabled = true;

        }

        /// <summary>
        /// 设置通道的状态
        /// </summary>
        /// <param name="modeOper"></param>
        /// <param name="color"></param>
        private void SetSingleSingeColor(int modeOper, ColorType color)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                switch (modeOper)
                {
                    case 1:
                        this.Ch1.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 2:
                        this.Ch2.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 3:
                        this.Ch3.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 4:
                        this.Ch4.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 5:
                        this.Ch5.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 6:
                        this.Ch6.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 7:
                        this.Ch7.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 8:
                        this.Ch8.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 9:
                        this.Ch9.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 10:
                        this.Ch10.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 11:
                        this.Ch11.BackColor = performanceTest.SetRunColorState(color);
                        break;
                    case 12:
                        this.Ch12.BackColor = performanceTest.SetRunColorState(color);
                        break;
                }
            }));
        }

        /// <summary>
        /// 设置通道默认颜色
        /// </summary>
        public void SetCHDefaultState()
        {
            this.Invoke(new MethodInvoker(() =>
            {
                Ch1.BackColor = Color.DarkGray;
                Ch2.BackColor = Color.DarkGray;
                Ch3.BackColor = Color.DarkGray;
                Ch4.BackColor = Color.DarkGray;
                Ch5.BackColor = Color.DarkGray;
                Ch6.BackColor = Color.DarkGray;
                Ch7.BackColor = Color.DarkGray;
                Ch8.BackColor = Color.DarkGray;
                Ch9.BackColor = Color.DarkGray;
                Ch10.BackColor = Color.DarkGray;
                Ch11.BackColor = Color.DarkGray;
                Ch12.BackColor = Color.DarkGray;
            }));
        }

        private void StopChangeBt_Click(object sender, EventArgs e)
        {
            tmerCh.Enabled = false;
            IsStop = true;
        }

        private void Button_Paint(object sender, PaintEventArgs e)
        {
            Button bt = sender as Button;
            GraphicsPath mygren = new GraphicsPath();
            System.Drawing.Rectangle rang = bt.ClientRectangle;
            rang.Inflate(-2, -1);
            e.Graphics.DrawEllipse(System.Drawing.Pens.BlanchedAlmond, rang);
            rang.Inflate(-2, -4);
            mygren.AddEllipse(rang);
            bt.Region = new Region(mygren);
        }
    }
}
